package leetcode_301_400;

import com.sun.org.apache.xpath.internal.operations.And;
import node.Node;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LeeCode_310 {
    public static void main(String[] args) {
//        System.out.println(findMinHeightTrees(4, new int[][]{{1, 0}, {1, 2}, {1, 3}}));
//        System.out.println(findMinHeightTrees(6, new int[][]{{3, 0}, {3, 1}, {3, 2},{3,4},{5,4}}));
//        System.out.println(findMinHeightTrees(5, new int[][]{{0, 1}, {0, 2}, {0, 3},{3,4}}));
        System.out.println(findMinHeightTrees(10, new int[][]{{0,3}, {1, 3}, {2, 3},{4,3},{5,3},{4,6},{4,7},{5,8},{5,9}}));
    }
    private static List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        if (n == 1) {
            res.add(0);
            return res;
        }
        List<Integer>[] map = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            map[i] = new ArrayList<>();
        }
        for (int[] e : edges) {
            map[e[0]].add(e[1]);
            map[e[1]].add(e[0]);
        }
        int[] max = new int[2];
        dfs(map, 0, 0, -1, max);
        int[] dep = new int[1];
        List<Integer> ans = new ArrayList<>();
        dfs2(map, max[1], -1, 0, new ArrayList<>(), dep, ans);
        int m = ans.size();
        if (m % 2 == 0){
            res.add(ans.get(m / 2));
            res.add(ans.get(m / 2 - 1));
        }else {
            res.add(ans.get(m / 2));
        }
        return res;
    }
    private static void dfs2(List<Integer>[] map, int now, int pre, int depth, List<Integer> list, int[] dep, List<Integer> ans){
        list.add(now);
        for (Integer next : map[now]) {
            if (map[now].size() == 1 && next == pre){
                if (depth > dep[0]){
                    while (ans.size() != 0)
                        ans.remove(ans.size() - 1);
                    ans.addAll(list);
                    dep[0] = depth;
                }
            }
            if (next != pre){
                dfs2(map, next, now, depth + 1, list, dep, ans);
            }
        }
        list.remove(list.size() - 1);
    }
    private static void dfs(List<Integer>[] map, int now, int depth, int pre, int[] max){
        for (Integer next : map[now]) {
            if (map[now].size() == 1 && next == pre){
                if (depth > max[0]){
                    max[0] = depth;
                    max[1] = now;
                }
                return;
            }
            if (next != pre) {
                dfs(map, next, depth + 1, now, max);
            }
        }
    }
}
